package com.maker.mcp.client.service.impl;

import cn.hutool.json.JSONUtil;
import com.maker.mcp.client.bean.SearXNGResponse;
import com.maker.mcp.client.bean.SearchResult;
import com.maker.mcp.client.service.SearXngService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class SearXngServiceImpl implements SearXngService {

    @Value("${internet.websearch.searxng.url}")
    private String SEARCH_URL;

    @Value("${internet.websearch.searxng.counts}")
    private Integer COUNTS;

    private  final OkHttpClient okHttpClient;
    @Override
    public List<SearchResult> search(String question) {
        //构建url
        HttpUrl url = HttpUrl.get(SEARCH_URL)
                .newBuilder()
                .addQueryParameter("q", question)
                .addQueryParameter("format","json")
                .build();
        log.info("搜索的url:{}",url);
        //构建request
        Request request = new Request.Builder()
                .url(url)
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
                .addHeader("Accept", "application/json, text/plain, */*")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                .build();
        try(Response response = okHttpClient.newCall(request).execute();) {
            if(!response.isSuccessful()){
                log.error("搜索失败:{}",response.code());
                throw new RuntimeException("搜索失败：HTTP "+ response.code());
            }

            if(response.body()!=null){
                String responseBody = response.body().string();
                SearXNGResponse searXNGResponse = JSONUtil.toBean(responseBody, SearXNGResponse.class);
                return dealResult(searXNGResponse.getResults());
            }
            log.error("搜索失败：{}",response.message());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Collections.emptyList();
    }


    private List<SearchResult>  dealResult(List<SearchResult> searchResults){
      return   searchResults
                        .subList(0,Math.min(COUNTS,searchResults.size()))
                        .parallelStream()
                        .sorted(Comparator.comparing(SearchResult::getScore).reversed())
                        .toList();
    }
}
